<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax的promise封装版本</title>
</head>
<body>
    <script>
        /* 在原先封装的基础上外包一个promise对象，在调用时在后执行then方法 */
        ajax({ 
            method : "jsonp" , 
            url : "https://www.baidu.com/sugrec",
            dataObj : {
                    pre:1,
                    p:3,
                    ie:"utf-8",
                    json:1,
                    prod:"pc",
                    from:"pc_web",
                    sugsid:"32218,1425,31672,32139,31254,32045,32230,32299,31639",
                    wd:"hello world",
                    req:2,
                    csor:5,
                    cb:"callback",
                    _:Date.now()
            },
            jsonpcallback : "callback"
        }).then(function(res){
            console.log(res);
        })

        // url封装
        function formate(url,dataObj){
            var start = true;
            var type = "GET";
            if(typeof url === 'object' && !(url instanceof Array)){
                dataObj = url;
                url = '';
                type = "POST";
            }

            // 2.参数拼接
            for(var key in dataObj){
                // get请求
                if(type === "GET"){
                    url += (start?"?":"&")+key+"="+dataObj[key];
                // post请求
                }else{
                    url += (start?"":"&")+key+"="+dataObj[key];
                }
                start = false;
            }
            return url;
        }

        // jsonp的ajax封装
        function ajax(options){
            // 创建promise对象
            return new Promise(function(resolved,reject){
                options = Object.assign({
        
                    method:'GET',
                    _callback:function(){},
                    url:'',
                    dataObj:{},
                    jsonpcallback:'callback',
                },options)

                // 1.请求方式为jsonp时
                if(options.method === "jsonp"){

                    var script = document.createElement("script");
                    script.src = formate(options.url,options.dataObj);
                    document.body.appendChild(script);

                    window[options.jsonpcallback] = function(data){
                        options._callback(data);
                        // 状态改变成功后把data作为参数传给resolved
                        resolved(data);
                    }
                    script.remove();
                }
                // 2.请求方式为get/post时
                else{
                    var xhr = new XMLHttpRequest();

                    xhr.open(options.method,options.method.toUpperCase() ==="GET" ? formate(options.url,options.dataObj) : options.url);

                    if(options.method.toUpperCase()==="POST"){
                        xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
                    }

                    xhr.send(options.method.toUpperCase() ==="POST" ? formate(options.dataObj) : '');

                    xhr.onreadystatechange = function(){
                        if(xhr.readyState===4&&/^2\d{2}$/.test(xhr.status)){
                            options._callback(xhr.responseText);
                            resolved(data);
                        }
                    }
                }
            })
            
        }
    </script>
</body>
</html>